<script setup>
import Broadcast from '@/components/Broadcast.vue';
import TopPlayer from '@/components/xinJi/TopPlayer.vue';
import PointPool_xinJi from '@/components/xinJi/PointPool.vue';
import PointPool from '@/components/PointPool.vue';
import Upgrade from '@/components/xinJi/Upgrade.vue';
import PlayerBox from '@/components/xinJi/PlayerBox.vue';
import xinJiLeaderboard from '@/components/xinJi/Leaderboard.vue';
import csLeaderboard from '@/components/cs/Leaderboard.vue';
import MapTable from '@/components/xinJi/MapTable.vue';

import { onMounted, onBeforeUnmount, ref, nextTick, toRaw } from 'vue';
import eventBus from 'vue3-eventbus';
import getApi from '@/api/modules/get';
import { sendMessage } from '@/utils/socketService';
import { getBadge, getBadgeStyle, getRank } from '@/utils/playerBox';
import { pollServerUpdates } from '@/utils/serverPolling';

const gameId = ref(0);
const anchorId = ref('');
const platformId = ref(1);
const pointPool = ref(0);
const messages = ref([]);
const leftPlayer = ref([]);
const rightPlayer = ref([]);
const lightboardAwards = ref([]);
const showLeaderboard = ref(false);     // 控制结算界面显示
const winTeam = ref('');                // 记录胜利队伍
const leaderboardType = ref('game');    // 排行榜类型：'game' | 'season' | 'settlement'
const currentSeason = ref(undefined);   // 当前赛季号
const redHpCurrent = ref(0);
const redHpMax = ref(-1);
const redName = ref('红方');
const blueHpCurrent = ref(0);
const blueHpMax = ref(-1);
const blueName = ref('蓝方');
const upgradeSwitch = ref(true)

const copyLeftPlayer = ref([]);
const copyRightPlayer = ref([]);
const copyMessages = ref([]);
const copyPointPool = ref(0);

const deepClone = (value) => JSON.parse(JSON.stringify(value));
const csLeaderboardRef = ref('');
const MapTableRef = ref(null);

let pollingTimer = null;

const runPolling = async () => {
    let effectiveWinTeam = null;
    if (redHpCurrent.value > blueHpCurrent.value) {
        effectiveWinTeam = 'red';
    } else if (blueHpCurrent.value > redHpCurrent.value) {
        effectiveWinTeam = 'blue';
    }

    await pollServerUpdates({
        leftPlayers: deepClone(leftPlayer.value),
        rightPlayers: deepClone(rightPlayer.value),
        messages: deepClone(messages.value),
        pointPool: deepClone(pointPool.value),
        anchorId: anchorId.value,
        gameId: gameId.value,
        winTeam: effectiveWinTeam,
        redName: redName.value,
        blueName: blueName.value
    });
};

const startPolling = () => {
    if (pollingTimer) return;
    void runPolling();
    pollingTimer = window.setInterval(() => {
        void runPolling();
    }, 3000);
};

const stopPolling = () => {
    if (pollingTimer) {
        clearInterval(pollingTimer);
        pollingTimer = null;
    }
};

// 接收子组件切换排行榜类型事件，更新父级状态
const handleLeaderboardTypeChange = (type) => {
    leaderboardType.value = type;
    // 切换类型时确保排行榜展示
    showLeaderboard.value = true;
};

// 防重复清除积分池的机制
const lastClearTime = ref(0);
const CLEAR_DEBOUNCE_TIME = (60*1000)*5; // 5分钟内不允许重复清除

// —— 本地持久化（基于 Uuid） ——
const STORAGE_PREFIX = 'GameUIState:';
const currentStorageKey = ref(null);
let fallbackPersistTimer = null;
let persistWorker = null;
let persistWorkerFailed = false;
const isWorkerSupported = typeof window !== 'undefined' && typeof window.Worker !== 'undefined';

const buildStorageKey = (uuid) => `${STORAGE_PREFIX}${uuid}`;

const clearStoredByPrefix = (prefix) => {
    try {
        const keysToRemove = [];
        for (let i = 0; i < localStorage.length; i++) {
            const k = localStorage.key(i);
            if (k && k.startsWith(prefix)) keysToRemove.push(k);
        }
        keysToRemove.forEach((k) => localStorage.removeItem(k));
    } catch (_) {
    }
};

const clearCurrentStoredState = () => {
    try {
        if (currentStorageKey.value) localStorage.removeItem(currentStorageKey.value);
    } catch (_) {
    }
    cancelScheduledPersist();
};

const buildPersistSnapshot = () => ({
    pointPool: pointPool.value,
    messages: toRaw(messages.value),
    leftPlayer: toRaw(leftPlayer.value),
    rightPlayer: toRaw(rightPlayer.value),
    redHpCurrent: redHpCurrent.value,
    redHpMax: redHpMax.value,
    redName: redName.value,
    blueHpCurrent: blueHpCurrent.value,
    blueHpMax: blueHpMax.value,
    blueName: blueName.value,
});

const persistState = (snapshot) => {
    if (!currentStorageKey.value) return;
    try {
        const payload = snapshot ?? buildPersistSnapshot();
        localStorage.setItem(currentStorageKey.value, JSON.stringify(payload));
    } catch (_) {
    }
};

const disposePersistWorker = () => {
    if (persistWorker) {
        persistWorker.terminate();
        persistWorker = null;
    }
};

const cancelScheduledPersist = () => {
    if (fallbackPersistTimer) {
        clearTimeout(fallbackPersistTimer);
        fallbackPersistTimer = null;
    }
    if (persistWorker) {
        try {
            persistWorker.postMessage({ type: 'cancel' });
        } catch (_) {
        }
    }
};

const ensurePersistWorker = () => {
    if (!isWorkerSupported || persistWorkerFailed) return null;
    if (persistWorker) return persistWorker;
    try {
        persistWorker = new Worker(new URL('../workers/statePersist.worker.js', import.meta.url), { type: 'module' });
        persistWorker.onmessage = (event) => {
            const { type, key, serialized, message } = event.data || {};
            if (type === 'persist') {
                if (!key || typeof serialized !== 'string') return;
                try {
                    localStorage.setItem(key, serialized);
                } catch (_) {
                }
            } else if (type === 'error') {
                console.error('[PersistWorker] serialize error:', message);
                persistWorkerFailed = true;
                disposePersistWorker();
                persistState();
            }
        };
        persistWorker.onerror = () => {
            persistWorkerFailed = true;
            disposePersistWorker();
        };
    } catch (_) {
        persistWorkerFailed = true;
        disposePersistWorker();
    }
    return persistWorker;
};

const schedulePersist = () => {
    if (!currentStorageKey.value) return;
    const worker = ensurePersistWorker();
    if (worker) {
        try {
            worker.postMessage({
                type: 'schedule',
                key: currentStorageKey.value,
                data: buildPersistSnapshot(),
                debounce: 300,
            });
            return;
        } catch (_) {
            persistWorkerFailed = true;
            disposePersistWorker();
        }
    }

    if (fallbackPersistTimer) return;
    fallbackPersistTimer = setTimeout(() => {
        fallbackPersistTimer = null;
        persistState();
    }, 300);
};

// 加载保存的数据
const loadSavedState = (saved) => {
    try {
        if (!saved) return;
        pointPool.value = Number(saved.pointPool) || 0;
        messages.value = Array.isArray(saved.messages) ? saved.messages : [];
        leftPlayer.value = Array.isArray(saved.leftPlayer) ? saved.leftPlayer : [];
        rightPlayer.value = Array.isArray(saved.rightPlayer) ? saved.rightPlayer : [];
        redHpCurrent.value = Number(saved.redHpCurrent) || 0;
        redHpMax.value = Number(saved.redHpMax) ?? -1;
        redName.value = saved.redName || '红方';
        blueHpCurrent.value = Number(saved.blueHpCurrent) || 0;
        blueHpMax.value = Number(saved.blueHpMax) ?? -1;
        blueName.value = saved.blueName || '蓝方';
    } catch (_) {
    }
};

const handleGetPlayerSeasonData = async (playerArray, game_id, message) => {
    const { userid_platform } = message;

    const updatePlayerByPlatform = (patch) => {
        const playerArrayRaw = toRaw(playerArray.value);
        const targetIndex = playerArrayRaw.findIndex(item => item.userid_platform == userid_platform);
        if (targetIndex === -1) {
            return null;
        }
        const updatedPlayer = { ...playerArrayRaw[targetIndex], ...patch };
        playerArray.value[targetIndex] = updatedPlayer;
        return updatedPlayer;
    };

    const markSeasonFetchFailed = () => {
        updatePlayerByPlatform({
            rank: null,
            total_players: 0,
            img_url: null,
            badge_style: null,
            season_points: 0,
            seasonDataReady: false
        });
    };

    try {
        const res = await getApi.getPlayerSeasonData({ userid_platform, game_id });
        if (res?.status === 200 && res.data?.data) {
            const { total_players, points, rank } = res.data.data;
            const normalizedPoints = Number(points) || 0;
            const updatedPlayer = updatePlayerByPlatform({
                rank,
                total_players,
                img_url: getBadge(normalizedPoints),
                badge_style: getBadgeStyle(normalizedPoints),
                season_points: normalizedPoints,
                seasonDataReady: true
            });
            if (updatedPlayer) {
                eventBus.emit('player-season-level-ready', {
                    player: updatedPlayer,
                    seasonPoints: normalizedPoints
                });
            }
        } else {
            markSeasonFetchFailed();
        }
    } catch (error) {
        console.error('[XinJiView] 获取玩家赛季数据失败:', error);
        markSeasonFetchFailed();
    }

    try {
        const weekRes = await getApi.getWeekLeaderboard({ userid_platform, game_id });
        if (weekRes?.status === 200 && weekRes.data?.data) {
            updatePlayerByPlatform({ week_rank: weekRes.data.data.rank });
        } else {
            updatePlayerByPlatform({ week_rank: null });
        }
    } catch (error) {
        console.error('[XinJiView] 获取周榜数据失败:', error);
        updatePlayerByPlatform({ week_rank: null });
    }

    // 异步补充数据后也进行一次保存（节流）
    schedulePersist();
};

// 处理关闭排行榜事件（不提交数据）
const handleCloseLeaderboard = (playerResults) => {
    // 重置状态
    leaderboardType.value = 'game';     // 重置为本局排行榜
    currentSeason.value = undefined;    // 清理赛季信息
    showLeaderboard.value = false;      // 关闭排行榜
};

const handleSocketMessage = (message) => {
    console.log('handleSocketMessage', message);
    let { type, team, player_id } = message;
    switch (type) {
        case 'system':
            gameId.value = message.game_id;
            anchorId.value = message.anchor_id;
            // 基于本次 Uuid 初始化存储键，尝试恢复；若不存在则清理历史并正常继续
            currentStorageKey.value = buildStorageKey(message.Uuid);
            try {
                const cached = currentStorageKey.value ? localStorage.getItem(currentStorageKey.value) : null;
                if (cached) {
                    upgradeSwitch.value = false;
                    const saved = JSON.parse(cached);
                    loadSavedState(saved);
                    setTimeout(() => {
                        messages.value = [...messages.value];
                        setTimeout(() => upgradeSwitch.value = true, 500)
                    }, 2000)
                } else {
                    // 清理以往同页面的历史数据
                    clearStoredByPrefix(STORAGE_PREFIX);
                    getApi.getAnchorData({anchor_id: anchorId.value, game_id: gameId.value})
                    .then(res => {
                        nextTick(() => {
                            pointPool.value = res.data.data.point_pool;
                            schedulePersist();
                        })
                    })
                }
            } catch (e) {
                // 异常情况下仍按正常流程拉取并保存
                clearStoredByPrefix(STORAGE_PREFIX);
                getApi.getAnchorData({anchor_id: anchorId.value, game_id: gameId.value})
                .then(res => {
                    nextTick(() => {
                        pointPool.value = res.data.data.point_pool;
                        schedulePersist();
                    })
                })
            }
            break;
        case 'changePlatformId':
            platformId.value = message.platformId;
            break
        case 'upUuid':
            clearCurrentStoredState();
            if (message.Uuid) {
                currentStorageKey.value = buildStorageKey(message.Uuid);
                schedulePersist();
            }
            break;
        case 'progress':
            let { userid_platform, progress } = message;
            let index = leftPlayer.value.findIndex(item => item.userid_platform === userid_platform);
            if (index != -1) {
                leftPlayer.value[index].progress = progress;
            }
            index = rightPlayer.value.findIndex(item => item.userid_platform === userid_platform);
            if (index != -1) {
                rightPlayer.value[index].progress = progress;
            }
            break;
        case 'add':
            if (team === 'red' && rightPlayer.value.length >= 1000 && rightPlayer.value.findIndex(item => item.player_id === player_id) == -1) return;
            if (team === 'blue' && leftPlayer.value.length >= 1000 && leftPlayer.value.findIndex(item => item.player_id === player_id) == -1) return;
            addPlayer(message);
            schedulePersist();
            break;
        case 'del':
            delPlayer(message);
            schedulePersist();
            break;
        case 'clear':
            const now = Date.now();
            if ((now - lastClearTime.value <= CLEAR_DEBOUNCE_TIME) || !messages.value.length || (!leftPlayer.value.length && !rightPlayer.value.length)) {
                return;
            }
            lastClearTime.value = now;
            leftPlayer.value  = [];
            rightPlayer.value = [];
            messages.value  = [];
            pointPool.value = pointPool.value == 0 ? 0 : Math.round(pointPool.value / 2); // 如果积分池不为0，则清空一半并四舍五入取整
            schedulePersist();
            break;
        case 'changeSort':
            {
                let { player_id, sortValue } = message;
                changePlayerSortValue(player_id, sortValue);
            }
            schedulePersist();
            break;
        case 'point':
            {
                let { player_id, userid_platform, gift_count, gift_point, gift_name } = message;
                if (rightPlayer.value.findIndex(item => item.userid_platform == userid_platform) != -1) {
                    let index = rightPlayer.value.findIndex(item => item.userid_platform == userid_platform);
                    if (rightPlayer.value[index].score == undefined) {
                        rightPlayer.value[index] = { ...rightPlayer.value[index], score: 0 } 
                    }
                    rightPlayer.value[index].score += gift_point * gift_count;
                    messages.value.push({ ...message, team: 'red' });
                    pointPool.value += gift_point * gift_count;
                    if (gift_name == '粉丝团灯牌') {
                        trySendFanLamp(rightPlayer.value[index]);
                    }
                } else if (leftPlayer.value.findIndex(item => item.userid_platform == userid_platform) != -1) {
                    let index = leftPlayer.value.findIndex(item => item.userid_platform == userid_platform);
                    if (leftPlayer.value[index].score == undefined) {
                        leftPlayer.value[index] = { ...leftPlayer.value[index], score: 0 } 
                    }
                    leftPlayer.value[index].score += gift_point * gift_count;
                    messages.value.push({ ...message, team: 'blue' });
                    pointPool.value += gift_point * gift_count;
                    if (gift_name == '粉丝团灯牌') {
                        trySendFanLamp(leftPlayer.value[index]);
                    }
                }
                schedulePersist();
            }
            break;
        case 'settle':
            let { winTeam: winner } = message;  // winTeam = 'red' or 'blue'        
            winTeam.value = winner;             // 保存胜利队伍
            
            copyLeftPlayer.value = deepClone(leftPlayer.value);
            copyRightPlayer.value = deepClone(rightPlayer.value);
            copyMessages.value = deepClone(messages.value);
            copyPointPool.value = deepClone(pointPool.value);

            // 重置排行榜类型为结算模式
            leaderboardType.value = 'settlement';
            showLeaderboard.value = true; // 显示结算界面
            // 结算时清除当前缓存，避免下次自动恢复旧局
            clearCurrentStoredState();
            MapTableRef.value?.close?.()
            break;
        case 'upHpBar':
            let { redTotal, redCurrent, blueTotal, blueCurrent } = message;
            redHpCurrent.value = redCurrent;
            redHpMax.value = redTotal;
            blueHpCurrent.value = blueCurrent;
            blueHpMax.value = blueTotal;
            redName.value = message.redName;
            blueName.value = message.blueName;
            schedulePersist();
            break;
        case 'leaderboard':
            let { scope } = message;
            leaderboardType.value = scope;
            showLeaderboard.value = true;
            copyLeftPlayer.value = deepClone(leftPlayer.value);
            copyRightPlayer.value = deepClone(rightPlayer.value);
            copyMessages.value = deepClone(messages.value);
            copyPointPool.value = deepClone(pointPool.value);
            MapTableRef.value?.close?.()
            break;
        case 'closeLeaderboard':
            handleCloseLeaderboard([]);
            break;
        case 'close':
            leftPlayer.value  = [];
            rightPlayer.value = [];
            messages.value  = [];
            pointPool.value = 0;
            winTeam.value = '';
            schedulePersist();
            break;
        case 'showMapTable':
            MapTableRef.value?.open?.()
            handleCloseLeaderboard([]);
            break;
        case 'closeMapTable':
            MapTableRef.value?.close?.()
            break;
    }
};

const addPlayer = (message) => {
    let { player_id, userid_platform, player_name, avatar, content, team, units, prefix = '', sortValue = 0 } = message;
    if (team === 'blue') {
        let index = leftPlayer.value.findIndex((item) => item.player_id === player_id);
        let exist_red = rightPlayer.value.findIndex((item) => item.player_id === player_id);
        // 更新玩家
        if (index !== -1) {
            leftPlayer.value[index].content = content;
            leftPlayer.value[index].sortValue = sortValue;
            leftPlayer.value[index].prefix = prefix;
            leftPlayer.value[index].units = units;
            eventBus.emit('cha-player', message);
            return;
        } 
        // 如果蓝方没有这个玩家，但是红方有这个玩家，则将红方这个玩家移动到蓝方
        else if (index == -1 && exist_red != -1) {
            leftPlayer.value.push({...rightPlayer.value[exist_red], team: 'blue'});
            rightPlayer.value.splice(exist_red, 1);
            nextTick(() => addPlayer(message));
            return;
        }
        // 添加新玩家
        else if (exist_red === -1) {
            leftPlayer.value.push({ player_id, userid_platform, player_name, avatar, content, team, units, prefix, sortValue, points: 0, seasonDataReady: null });
            nextTick(() => {
                handleGetPlayerSeasonData(leftPlayer, gameId.value, message);
            })
            eventBus.emit('add-player', message);
        }
    } else if (team === 'red') {
        let index = rightPlayer.value.findIndex((item) => item.player_id === player_id);
        let exist_blue = leftPlayer.value.findIndex((item) => item.player_id === player_id);
        // 更新玩家
        if (index !== -1) {
            rightPlayer.value[index].content = content;
            rightPlayer.value[index].sortValue = sortValue;
            rightPlayer.value[index].prefix = prefix;
            rightPlayer.value[index].units = units;
            eventBus.emit('cha-player', message);
            return;
        } 
        // 如果红方没有这个玩家，但是蓝方有这个玩家，则将蓝方这个玩家移动到红方
        else if (index == -1 && exist_blue != -1) {
            rightPlayer.value.push({...leftPlayer.value[exist_blue], team: 'red'});
            leftPlayer.value.splice(exist_blue, 1);
            nextTick(() => addPlayer(message));
            return;
        }
        // 添加新玩家
        else if (exist_blue === -1) {
            rightPlayer.value.push({ player_id, userid_platform, player_name, avatar, content, team, units, prefix, sortValue, points: 0, seasonDataReady: null });
            nextTick(() => {
                handleGetPlayerSeasonData(rightPlayer, gameId.value, message);
            })
            eventBus.emit('add-player', message);
        }
    }
};

const delPlayer = (message) => {
    let { player_id } = message;
    let index = leftPlayer.value.findIndex((item) => item.player_id === player_id);
    if (index !== -1) {
        leftPlayer.value.splice(index, 1);
        eventBus.emit('del-player', message);
        return;
    }
    index = rightPlayer.value.findIndex((item) => item.player_id === player_id);
    if (index !== -1) {
        rightPlayer.value.splice(index, 1);
        eventBus.emit('del-player', message);
    }
};

const changePlayerSortValue = (messageOrId, newSortValue) => {
    let player_id, sortValue;
    if (typeof messageOrId === 'object') {
        ({ player_id, sortValue } = messageOrId);
    } else {
        player_id = messageOrId;
        sortValue = newSortValue;
    }
    let player =
        leftPlayer.value.find((item) => item.player_id === player_id) ||
        rightPlayer.value.find((item) => item.player_id === player_id);
    if (player) {
        player.sortValue = sortValue;
    }
};

const findLightboardAward = (gameIdVal, platformVal) => {
    if (!lightboardAwards.value || !Array.isArray(lightboardAwards.value)) return null;
    const gid = Number(gameIdVal);
    const plat = Number(platformVal);
    if (!Number.isFinite(gid) || !Number.isFinite(plat)) return null;
    const gameHit = lightboardAwards.value.find(g => Number(g.game_id) === gid);
    if (!gameHit) return null;
    const platforms = Array.isArray(gameHit.platforms) ? gameHit.platforms : [];
    const platHit = platforms.find(p => Number(p.platform) === plat);
    if (!platHit) return null;
    const awards = Array.isArray(platHit.awards) ? platHit.awards : [];
    if (!awards.length) return null;
    return awards
        .map(a => ({ ...a, level: Number(a.level) }))
        .filter(a => Number.isFinite(a.level))
        .sort((a, b) => b.level - a.level)[0];
};

const pendingFanLamp = new Set();

const sendLightboardAwardMessage = (playerData, platformVal) => {
    if (!playerData) return;
    const seasonPoints = Number(playerData.season_points ?? 0);
    const realtimePoints = Number(playerData.score ?? 0);
    const totalPoints =
        (Number.isFinite(seasonPoints) ? seasonPoints : 0) + (Number.isFinite(realtimePoints) ? realtimePoints : 0);
    if (!Number.isFinite(totalPoints) || totalPoints <= 0) return;
    const level = getRank(totalPoints);
    const award = findLightboardAward(gameId.value, platformVal);
    if (!award || level <= award.level) return;
    const nickname = playerData.player_name ?? '';
    const normalizedPlatformId = playerData.userid_platform ?? '';
    const normalizedGiftName = award.giftName ?? '';
    const normalizedGiftCount = award.gift_num || 1;
    const isLikeGift = normalizedGiftName === '点赞' || normalizedGiftName.toLowerCase() === 'like';
    const payload = isLikeGift
        ? {
            type: 'lightBoardAwardGift',
            Type: 2,
            Data: {
                User: { Nickname: nickname },
                LikeCount: normalizedGiftCount
            }
        }
        : {
            type: 'lightBoardAwardGift',
            Type: 5,
            Data: {
                User: {
                    Nickname: nickname,
                    DisplayId: normalizedPlatformId,
                    Avatar: playerData.avatar
                },
                GiftName: normalizedGiftName,
                GiftCount: normalizedGiftCount,
            }
        };
    sendMessage(payload);
};

const trySendFanLamp = (playerData) => {
    if (!playerData) return;
    const seasonPoints = Number(playerData.season_points ?? playerData.seasonPoints ?? 0);
    const realtimePoints = Number(playerData.score ?? playerData.points ?? 0);
    const totalPoints =
        (Number.isFinite(seasonPoints) ? seasonPoints : 0) + (Number.isFinite(realtimePoints) ? realtimePoints : 0);
    if (!Number.isFinite(totalPoints) || totalPoints <= 0) {
        if (playerData.userid_platform) pendingFanLamp.add(String(playerData.userid_platform));
        return;
    }
    sendLightboardAwardMessage(playerData, platformId.value);
    if (playerData.userid_platform) pendingFanLamp.delete(String(playerData.userid_platform));
};

const loadAllLightBoardAwards = async () => {
    try {
        const res = await getApi.getAllLightBoardAwards();
        const games = res?.data?.games;
        lightboardAwards.value = Array.isArray(games) ? games : [];
    } catch (error) {
        console.error('[XinJiView] 获取灯牌奖励配置失败:', error);
        lightboardAwards.value = [];
    }
};

onMounted(async () => {
    eventBus.on('socket-message', handleSocketMessage);
    eventBus.on('player-season-level-ready', ({ player }) => {
        if (player?.userid_platform && pendingFanLamp.has(String(player.userid_platform))) {
            trySendFanLamp(player);
        }
    });
    startPolling();
    void loadAllLightBoardAwards();
});

onBeforeUnmount(() => {
    stopPolling();
    cancelScheduledPersist();
    persistState();
    disposePersistWorker();
});

</script>

<template>
    <div class="app-container">
        
        <!-- 玩家列表 -->
        <!-- <PlayerList 
            :leftPlayer="leftPlayer"
            :rightPlayer="rightPlayer"
            :hidePlayer="false"
            :showLeftPlayers="true"
            :showRightPlayers="true" /> -->
            
        <!-- 击杀播报 -->
        <!-- <Broadcast 
            :leftPlayer="leftPlayer" 
            :rightPlayer="rightPlayer" /> -->

        <!-- 积分池 -->
        <PointPool_xinJi
            v-if="gameId == 13 || gameId == 10"
            :points="pointPool" 
            :scale="1" 
            :redHpCurrent="redHpCurrent" 
            :redHpMax="redHpMax" 
            :redName="redName" 
            :blueHpCurrent="blueHpCurrent" 
            :blueHpMax="blueHpMax" 
            :blueName="blueName" />
            
        <PointPool
            v-else
            :points="pointPool" 
            :scale="1" 
            :redHpCurrent="redHpCurrent" 
            :redHpMax="redHpMax" 
            :redName="redName" 
            :blueHpCurrent="blueHpCurrent" 
            :blueHpMax="blueHpMax" 
            :blueName="blueName" />

        <TopPlayer 
            :gameId="gameId"
            :leaderboardType="leaderboardType"
            :visible="showLeaderboard" />

        <Upgrade
            :gameId="gameId" 
            :platformId="platformId"
            :lightboard-awards="lightboardAwards"
            :upgrade-switch="upgradeSwitch" />
        
        <!-- 玩家框 -->
        <PlayerBox 
            :bluePlayers="rightPlayer" 
            :redPlayers="leftPlayer" 
            :scale="1"
            :redHpCurrent="redHpCurrent"
            :blueHpCurrent="blueHpCurrent"
            :pointPool="pointPool" 
            :messages="messages"
            :winTeam="winTeam"
            :gameId="gameId" />

        <!-- cs排行榜 -->
        <csLeaderboard 
            v-if="gameId == 6"
            ref="csLeaderboardRef"
            :anchorId="anchorId"
            :leftPlayer="copyLeftPlayer" 
            :rightPlayer="copyRightPlayer" 
            :messages="copyMessages"
            :pointPool="copyPointPool"
            :winTeam="winTeam"
            :visible="showLeaderboard"
            :leaderboardType="leaderboardType"
            :gameId="gameId"
            :redHpCurrent="redHpCurrent"
            :blueHpCurrent="blueHpCurrent"
            :season="currentSeason"
            @display-completed="handleCloseLeaderboard" />

        <div style="position: fixed; left: 0; top: 0;" 
        v-draggable-resizable="{
            storageKey: 'Leaderboard',
            controlsPosition: 'top',
            hideHintText: '排行榜',
            scaleStep: 0.1,
            layer: 1,
            initSize: 0.65,
            top: '-22%',
            left: '3%',
        }">
            <!-- 星际排行榜 -->
            <xinJiLeaderboard
                v-if="gameId != 6"
                :anchorId="anchorId"
                :leftPlayer="copyLeftPlayer" 
                :rightPlayer="copyRightPlayer" 
                :messages="copyMessages"
                :pointPool="copyPointPool"
                :winTeam="winTeam"
                :visible="showLeaderboard"
                :leaderboardType="leaderboardType"
                :gameId="gameId"
                :redHpCurrent="redHpCurrent"
                :redName="redName"
                :blueHpCurrent="blueHpCurrent"
                :blueName="blueName"
                :season="currentSeason"
                @update:leaderboardType="handleLeaderboardTypeChange"
                @change-leaderboard-type="handleLeaderboardTypeChange"
                @display-completed="handleCloseLeaderboard" />
            <MapTable
                ref="MapTableRef"
                :gameId="gameId" />
        </div>
    </div>
</template>

<style scoped>
.app-container {
    display: flex;
    justify-content: space-between;
    width: 100%;
    max-width: 100vw;
    min-height: 100vh;
    position: relative;
}
</style>
